package com.julyup.core.exception;

import com.julyup.core.constant.ErrorEnum;
import com.julyup.core.util.ResponseObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@ResponseBody
public class GlobalExceptionHandler {

  private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

  /**
   * 统一处理所有未处理异常
   *
   * @param e
   * @return
   */
  @ExceptionHandler({Exception.class})
  @ResponseStatus(HttpStatus.OK)
  public ResponseObject handleGlobalException(Exception e) {
    ResponseObject responseObject = ResponseObject.fail(ErrorEnum.SERVER_ERROR);
    e.printStackTrace();
    return responseObject;
  }

  /**
   * 自定义异常
   *
   * @param e
   * @return
   */
  @ExceptionHandler(value = {BusinessException.class})
  @ResponseStatus(HttpStatus.OK)
  public ResponseObject handleRestException(BusinessException e) {
    ResponseObject responseObject = ResponseObject.fail(e.getError());
    return responseObject;
  }
}
